import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicInteger;


public class FifoLock implements AbstractLock{
	
	
	Queue<String> que = new ArrayDeque<String>();

	
	AtomicInteger reades = new AtomicInteger(0);
	
	String current = "alalalal";
	

	@Override
	public  synchronized void readerIn() {
		
		beg();
		reades.incrementAndGet();
		next();
	}

	@Override
	public synchronized void readerout() {
		reades.decrementAndGet();
		notifyAll();
	}

	@Override
	public  synchronized void witerIn() {
		beg();
		
		while(reades.intValue() > 0){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public synchronized void writerout() {
		next();
	}

	
	public synchronized void next(){
		synchronized (current) {
			current = que.poll();
		}
		notifyAll();
	}
	
	public synchronized void beg(){
		String name = Thread.currentThread().getName();
		
		if (current.equals("alalalal")) {
			synchronized (current) {
				current = name;
			}
			
		}
		
		que.offer(name);
		
		while (!current.equals(name)){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	
}
